package net.flowas.modulecart.rest;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;


/**
 * 
 */
public abstract class AbstractEndpoint<T>
{
   protected EntityManager entityManager= Persistence.createEntityManagerFactory ("cartPU").createEntityManager();

   @POST
   @Consumes("application/json")
   public T create(T entity)
   {
      entityManager.persist(entity);
      return entity;
   }
   
   @DELETE
   @Path("/{id:[0-9][0-9]*}")
   public void deleteById(@PathParam("id") Long id)
   {
      T entity = entityManager.find(getType(), id);
      if (entity == null)
      {
         //return Response.status(Status.NOT_FOUND).build();
      }
      entityManager.remove(entity);
      //return Response.noContent().build();
   }

   @GET
   @Path("/{id:[0-9][0-9]*}")
   @Produces("application/json")
   public T findById(@PathParam("id") Long id)
   {
	  String typeName= getType().getSimpleName();
	  TypedQuery<T> findByIdQuery = entityManager.createQuery("SELECT c FROM "+typeName+" c  WHERE c.id = :entityId ORDER BY c.id", getType());
      findByIdQuery.setParameter("entityId", id);
      T entity;
      try
      {
         entity = findByIdQuery.getSingleResult();
      }
      catch (NoResultException nre)
      {
         entity = null;
      }
      if (entity == null)
      {
         //return Response.status(Status.NOT_FOUND).build();
      }
      return entity;
   }
      
   @PUT
   @Path("/{id:[0-9][0-9]*}")
   @Consumes("application/json")
   public void update(T entity)
   {
      entity = entityManager.merge(entity);
   }
   protected abstract Class<T> getType();
}